package com.eureka.provider.proxy;/*
 *@Description
 *@Author:Sam
 *@creat-time:2021/4/12 14:41
 */

import java.lang.reflect.*;

//动态代理类
public class CalculatorProxy {
    Calculator calculator;

    public CalculatorProxy(Calculator c) throws Exception {
        calculator=(Calculator) getProxy(c);
    }
    public int add(int a,int b){
        return calculator.add(a,b);
    }

    private static Object getProxy(final Object target) throws Exception {
        Object proxy = Proxy.newProxyInstance(
                target.getClass().getClassLoader(),/*类加载器*/
                target.getClass().getInterfaces(),/*让代理对象和目标对象实现相同接口*/
                new InvocationHandler(){/*代理对象的方法最终都会被JVM导向它的invoke方法*/
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println(method.getName() + "方法开始执行...");
                        Object result = method.invoke(target, args);
                        System.out.println(result);
                        System.out.println(method.getName() + "方法执行结束...");
                        return result;
                    }
                }
        );
        System.out.println(proxy.getClass().getName());
        return proxy;
    }

    public static void main(String[] args) throws Exception {
        //动态代理
        CalculatorProxy calculatorProxy=new CalculatorProxy(new CalculatorImp());
        calculatorProxy.add(1,2);
    }

}
